<?php
/**
 * Created by PhpStorm.
 * User: HS032
 * Date: 2020/7/7
 * Time: 10:26
 */

namespace pay\modules\backend\controllers;


use pay\libs\WxPayApi;
use pay\modules\backend\models\Order;
use pay\modules\backend\models\OrderDetails;
use pay\modules\backend\models\OrderInfo;
use pay\modules\backend\models\OrderSearch;
use pay\libs\Tools;
use pay\modules\backend\models\RefundOrderLog;
use Yii;


class PayOrderController extends BasicController
{

    /*** 订单列表
     * @return false|string
     */
    public function actionTest()
    {
        $get = Yii::$app->request->get();
        if (isset($get['appId']) and !empty($get['appId'])){
            $get['app_id'] = $this->getAppId($get['appId']);
        }else{
            return Tools::showRes(99,'参数有误');
        }
        if (!isset($get['app_id']) || empty($get['app_id'])){
            return Tools::showRes(99,'实例id不能为空');
        }
        $page = isset($get['page'])?(int)$get['page']:1;
        $pageSize = isset($get['size'])?(int)$get['size']:10;

        $orderModel = (new OrderSearch())->search($get)->andFilterWhere(['app_id' => $get['app_id']]);
        $count = $orderModel->count();
        $orderList = $orderModel->offset($pageSize * ($page - 1))->orderBy(['oid' => SORT_DESC])->limit($pageSize)->asArray()->all();

        return Tools::showRes(0,'success',[
            'orderList' => $orderList,
            'page' => $page,
            'size' => $pageSize,
            'count' => $count,
        ]);
    }


    public function actionOrderList()
    {
        $get = Yii::$app->request->get();
        if (isset($get['appId']) and !empty($get['appId'])){
            $get['app_id'] = $this->getAppId($get['appId']);
        }else{
            return Tools::showRes(99,'参数有误');
        }
        if (!isset($get['app_id']) || empty($get['app_id'])){
            return Tools::showRes(99,'实例id不能为空');
        }
        $page = isset($get['page'])?(int)$get['page']:1;
        $pageSize = isset($get['size'])?(int)$get['size']:10;

        $orderModel = (new OrderSearch())->search($get)->andFilterWhere(['app_id' => $get['app_id']]);
        $count = $orderModel->count();
        $orderList = $orderModel->offset($pageSize * ($page - 1))->with(['details'])->orderBy(['oid' => SORT_DESC])->limit($pageSize)->asArray()->all();

        foreach ($orderList as $key => $val){
            $orderList[$key]['from'] = $val['details']['from'];
            $orderList[$key]['success_time'] = $val['pay_times'];
            $orderList[$key]['pay_money'] = $val['details']['pay_money'];
            if ($val['pay_status'] == 3 and $val['details']['is_refund'] == 2){
                $orderList[$key]['is_refund'] = '1';
            }else{
                $orderList[$key]['is_refund'] = '2';
            }
            unset($orderList[$key]['details']);
        }
//        var_dump($orderList);die;
        return Tools::showRes(0,'success',[
            'orderList' => $orderList,
            'page' => $page,
            'size' => $pageSize,
            'count' => $count,
        ]);
    }


    /**** 退款接口
     * aid             aid
     * pay_order_sn    支付单号
     * @return false|string
     */
    public function actionRefundOrder()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            if (!isset($post['aid']) || empty($post['aid'])){
                return Tools::showRes(99,'参数有误');
            }
            if (!isset($post['pay_order_sn']) || empty($post['pay_order_sn'])){
                return Tools::showRes(99,'参数有误');
            }
            $orderInfo = Order::find()->where('aid = :id and pay_order_sn = :paysn',[':id' => $post['aid'],':paysn' => $post['pay_order_sn']])
                ->joinWith('details')
                ->asArray()->one();
//            var_dump($orderInfo);die;
            if (!empty($orderInfo) and $orderInfo['pay_status'] == 3 and $orderInfo['details']['is_refund'] == 2){
                $params = [
                    'paySerialId' => $post['pay_order_sn'],
                    'refundUserSerial' => 'rf'.Tools::createSn(),
                    'refundFee' => $orderInfo['real_money'],
                    'totalFee' => $orderInfo['real_money'],
                    'payUserId' => isset(Yii::$app->session->get('loginInfo')->userInfo['username'])?Yii::$app->session->get('loginInfo')->userInfo['username']:"123",
                ];
                $refuncOrderLogModel = new RefundOrderLog();

                $wxPayApi = new WxPayApi($orderInfo['details']['channel_id']);
                $result = $wxPayApi->refund($params);
                if (!$refund_id = $refuncOrderLogModel->addLog($params,$result)){
                    if ($refuncOrderLogModel->hasErrors()){
                        return Tools::showRes(99,$refuncOrderLogModel->getErrors());
                    }else{
                        return Tools::showRes(99,'添加失败');
                    }
                }
                if ($result['code'] === 0 and $result['msg']['refund_id'] != ''){
                    $orderModels = Order::findOne($orderInfo['oid']);
                    $orderModels->pay_status = 5;
                    $orderModels->ref_order_sn = $params['refundUserSerial'];
                    $orderModels->save(0);
                    $orderDetailsModel = new OrderDetails();
                    $orderDetailsModel->addRefundInfo($orderInfo['oid'],$params['real_money']);

                    if($orderModels->app_id==4){//德清的退款
                        $remark = json_decode($orderDetailsModel->remake,true);
                        if($remark){
                            $orderid = $remark['oid'];
                            $res = $this->curlPost('https://xxxnk.klygf.com/dq_ticket_inter/inteface/routine/cancelOrders.json' ,['orderid'=>$orderid]);
                            return Tools::showRes(0,'第三方成功退票');
                        }
                    }

                    return Tools::showRes(0,'退款成功');

                }else{
                    return Tools::showRes(99,$result['msg']);
                }
            }else{
                return Tools::showRes(99,'退款失败，数据有误');
            }
        }
    }



    public function actionDqRefund()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            if (!isset($post['aid']) || empty($post['aid'])){
                return Tools::showRes(99,'参数有误');
            }
            if (!isset($post['pay_order_sn']) || empty($post['pay_order_sn'])){
                return Tools::showRes(99,'参数有误');
            }
            $orderInfo = Order::find()->where('aid = :id and pay_order_sn = :paysn',[':id' => $post['aid'],':paysn' => $post['pay_order_sn']])
                ->joinWith('details')
                ->asArray()->one();
//            var_dump($orderInfo);die;
            if (!empty($orderInfo) and $orderInfo['pay_status'] == 3 and $orderInfo['details']['is_refund'] == 2){
                $params = [
                    'paySerialId' => $post['pay_order_sn'],
                    'refundUserSerial' => 'rf'.Tools::createSn(),
                    'refundFee' => $orderInfo['real_money'],
                    'totalFee' => $orderInfo['real_money'],
                    'payUserId' => isset(Yii::$app->session->get('loginInfo')->userInfo['username'])?Yii::$app->session->get('loginInfo')->userInfo['username']:"123",
                ];
                $refuncOrderLogModel = new RefundOrderLog();

                $wxPayApi = new WxPayApi($orderInfo['details']['channel_id']);
                $result = $wxPayApi->refund($params);
                if (!$refund_id = $refuncOrderLogModel->addLog($params,$result)){
                    if ($refuncOrderLogModel->hasErrors()){
                        return Tools::showRes(99,$refuncOrderLogModel->getErrors());
                    }else{
                        return Tools::showRes(99,'添加失败');
                    }
                }
                if ($result['code'] === 0 and $result['msg']['refund_id'] != ''){
                    $orderModels = Order::findOne($orderInfo['oid']);
                    $orderModels->pay_status = 5;
                    $orderModels->ref_order_sn = $params['refundUserSerial'];
                    $orderModels->save(0);
                    $orderDetailsModel = new OrderDetails();
                    $orderDetailsModel->addRefundInfo($orderInfo['oid'],$params['real_money']);

                    if($orderModels->app_id==4){//德清的退款
                        $remark = json_decode($orderDetailsModel->remake,true);
                        if($remark){
                            $orderid = $remark['oid'];
                            $res = $this->curlPost('https://xxxnk.klygf.com/dq_ticket_inter/inteface/routine/cancelOrders.json' ,['orderid'=>$orderid]);
                        }
                    }
                    return Tools::showRes(0,'退款成功');
                }else{
                    return Tools::showRes(99,$result['msg']);
                }
            }else{
                return Tools::showRes(99,'退款失败，数据有误');
            }
        }
    }


    private  function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
            // $postData = json_encode($postData);
        }

        // $headers = ["Content-type: application/json"];
        $headers = ["Content-type: application/x-www-form-urlencoded"];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }

        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $data = curl_exec($ch);
        if(curl_error($ch)){
            return false;
        }

        curl_close($ch);

        return $data;
    }
    
}